from django.db import models
from datetime import datetime


class AbstractBaseModel(models.Model):

    def float_2_str(self, val):
        if val == 0:
            return str(int(val))
        return '%.2f' % val

    def get_field_property(self, field, key):
        if not hasattr(self, field):
            return ''
        return getattr(getattr(self, field), key, '')

    def format_datetime(self, date, format='%Y-%m-%d'):
        if not date:
            return ''
        return date.strftime(format)

    class Meta:
        abstract = True


class BaseModel(AbstractBaseModel):
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)
    state = models.IntegerField(default=0)
    show_order = models.IntegerField(default=0)

    class Meta:
        abstract = True


class BaseSimpleModel(AbstractBaseModel):
    create_time = models.DateTimeField('创建时间', null=False, auto_now_add=True)
    update_time = models.DateTimeField('修改时间', null=False, auto_now=True)

    class Meta:
        abstract = True


class Advertisement(BaseModel):
    name = models.CharField('标题', max_length=256)
    category_id = models.IntegerField('1首页', default=1)
    image_file = models.CharField('封面', max_length=255)
    url = models.CharField('跳转地址', max_length=255)

    class Meta:
        db_table = 'advertisements'

    def to_dict(self, photo_style=''):
        d = dict(
            name=self.name,
            image_file=self.image_file,
            url=self.url,
        )

        if not d['image_file']:
            d['image_file'] = 'https://media.joyfulmedia.cn/010.jpg'
        if photo_style:
            d['image_file'] += photo_style
        return d


class User(BaseSimpleModel):
    NORMAL, MANAGER, TEAM, PRODUCER = 0, 1, 2, 3
    openid = models.CharField(unique=True, max_length=64)
    nickname = models.CharField(max_length=256, default='')
    gender = models.IntegerField(default=9)
    language = models.CharField(max_length=256, default='')
    city = models.CharField(max_length=256, default='')
    province = models.CharField(max_length=256, default='')
    country = models.CharField(max_length=256, default='')
    avatar = models.CharField(max_length=256, default='')
    contact_name = models.CharField(max_length=32, default='')
    phone = models.CharField(max_length=32, default='')
    user_state = models.IntegerField('0普通用户1客户经理2团队老大3普通生产者', default=0)
    user_from = models.IntegerField('0普通用户1客户经理2生产', default=0)
    enter_state = models.IntegerField('0未入驻1已入驻', default=0)
    enter_applications = models.CharField('入驻申请: 申请类型|申请参数', max_length=255, default='')

    class Meta:
        db_table = 'users'

    def to_simple_dict(self):
        return {
            'nickname': self.nickname,
            'avatar': self.avatar,

        }

    def to_dict(self):
        return dict(
            id=self.id,
            openid=self.openid,
            nickname=self.nickname,
            gender=self.gender,
            language=self.language,
            city=self.city,
            province=self.province,
            country=self.country,
            avatar=self.avatar,
            contact_name=self.contact_name,
            phone=self.phone,
            user_state=self.user_state,

        )


# 角色表比如1级导演2级导演3级导演
class Element(BaseModel):
    name = models.CharField(max_length=256, default='')
    url = models.CharField(max_length=512, default='')
    unit = models.CharField('单位人、台', max_length=256, default='')
    price = models.IntegerField(default=0)
    type = models.IntegerField('类型1角色2设备', default=1)
    level = models.IntegerField(default=1)
    desc = models.CharField(max_length=512, default='')

    TYPE_PERSON, TYPE_EQUIP = 1, 2

    def to_dict(self):
        return dict(
            id=self.id,
            name=self.name,
            url=self.url,
            unit=self.unit,
            type=self.type,
            level=self.level,
            num=0,
            desc=self.desc,
        )

    class Meta:
        db_table = 'elements'


# 类似对应导演团队里面的，国内一流导演团队，国际一流导演团队，全球一流导演团队
class Option(BaseModel):
    title = models.CharField(max_length=256, default='')
    desc = models.CharField(max_length=512, default='')
    elements = models.ManyToManyField(Element, through='OptionElement')


    def to_dict(self):
        return  dict(
            id=self.id,
            title=self.title,
            desc=self.desc,
            elements = [key.to_dict() for key in OptionElement.objects.filter(option=self).all()]
        )


    class Meta:
        db_table = 'options'


# #待补充
class OptionElement(models.Model):
    element = models.ForeignKey(Element, on_delete=models.CASCADE)
    option = models.ForeignKey(Option, on_delete=models.CASCADE)
    num = models.IntegerField('元素数量')

    def to_dict(self):
        data = self.element.to_dict()
        data['num'] = self.num
        return data

    class Meta:
        db_table = 'option_elements'


# 比如导演，拍摄，设备
class Category(BaseModel):
    name = models.CharField(max_length=256, default='')
    elements = models.ManyToManyField(Element, verbose_name='分类对应的角色，比如导演有1级导演2级导演3及导演1级策划2级策划', null=True, default='', blank='')
    options = models.ManyToManyField(Option, verbose_name='导演对应的专业策划团队、省级卫视策划院队、国内4a级策划团队', null=True, default='', blank='')

    class Meta:
        db_table = 'categorys'
    def to_dict(self):
        return dict(
            name=self.name,
            elements=[key.to_dict() for key in self.elements.all()],
            options=[key.to_dict() for key in self.options.all()]

        )

# 用户反馈
class Feedback(BaseSimpleModel):
    content = models.CharField(max_length=512, default='')
    openid = models.CharField(max_length=64, default='')

    class Meta:
        db_table = 'feedbacks'


# 视频馆商品分类
class GCategory(BaseModel):
    name = models.CharField(max_length=512)

    def to_dict(self):
        d = {
            'id': self.id,
            'name': self.name,
        }
        return d

    class Meta:
        db_table = 'gcategorys'


# 视频馆商品banner
class Banner(BaseModel):
    name = models.CharField(max_length=256)
    url = models.CharField(max_length=255)

    def to_dict(self):
        d = {
            'url': self.url,
            'name': self.name,
        }
        if self.url:
            d['url'] += '/750_480'
        return d

    class Meta:
        db_table = 'banners'


# 视频馆商品价格规格
class Price(BaseModel):
    name = models.CharField(max_length=256, default='')
    price = models.IntegerField(default=0)
    transaction_price = models.IntegerField(default=0)
    unit = models.CharField(max_length=256, default='')
    inventory = models.IntegerField(default=0)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'price': self.price,
            'transaction_price': self.transaction_price,
            'unit': self.unit,
            'inventory': self.inventory,
        }

    class Meta:
        db_table = 'prices'



# 视频馆商品
class Goods(BaseModel):
    name = models.CharField(max_length=256)
    image_file = models.CharField(max_length=255)
    tags = models.CharField(max_length=255, default='')
    sales = models.IntegerField(default=0)
    ini_sales = models.IntegerField(default=0)
    detail = models.CharField(max_length=2048, default='')
    content = models.CharField(max_length=512, default='')
    city = models.CharField(max_length=512, default='')
    category = models.ForeignKey(GCategory, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    banners = models.ManyToManyField(Banner, verbose_name='商品对应的banner', null=True, default='', blank='')
    prices = models.ManyToManyField(Price, verbose_name='商品对应的规格', null=True, default='', blank='')

    def to_dict(self, photo_style='', type=1):
        d = {
            'id': self.id,
            'name': self.name,
            'image_file': self.image_file,
            'sales': self.sales,
            'city': self.city,
            'content': self.content,

        }
        if self.tags:
            d['tags'] = self.tags.split(','),
        if self.detail:
            details = self.detail.split(',')
            dd = []
            for v in details:
                dd.append(v + '/750')
            d['detail'] = dd
        if photo_style:
            d['image_file'] += photo_style
        # if d['detail']:
        #     d['detail'] += '/750'

        if self.prices and type == 1:
            d['price'] = self.prices.order_by('show_order').first().to_dict()
        if self.prices and type == 2:
            d['price'] = [key.to_dict() for key in self.prices.all()]
        if self.banners:
            d['banner'] = [key.to_dict() for key in self.banners.all()]
        return d

    class Meta:
        db_table = 'goods'


# 视频馆商品订单
class GOrder(BaseModel):
    status = models.IntegerField()
    goods = models.ForeignKey(Goods, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    price = models.ForeignKey(Price, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    user = models.ForeignKey(User, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    weixin_order_id = models.CharField(max_length=64, default='')
    order_id = models.CharField(max_length=64, default='')
    num = models.IntegerField(default=1)
    pay_price = models.FloatField(default=0)
    pay_amount = models.FloatField(default=0)
    remark = models.CharField(max_length=512, default='')

    def to_dict(self, type=1, photo_style=''):
        d = dict(
            id=self.id,
            create_time=self.create_time,
            price=self.pay_price,
            pay_amount=self.pay_amount,
            remark=self.remark,
            status=self.status,
            num=self.num,

        )
        if self.price:
            d['good_price'] = self.price.to_dict()
        if self.goods:
            d['goods'] = self.goods.to_dict()
        return d


    class Meta:
        db_table = 'gorders'


# 视频馆商品评论
class Comment(BaseSimpleModel):
    content = models.CharField(max_length=512)
    price = models.ForeignKey(Price, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    user = models.ForeignKey(User, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    goods = models.ForeignKey(Goods, verbose_name='商品', null=True,  on_delete=models.DO_NOTHING)

    def to_dict(self, photo_style=''):
        d = {
            'id': self.id,
            'create_time': self.create_time,
            'content': self.content,

        }
        if self.price:
            d['type'] = self.price.to_dict()
        if self.goods:
            d['goods'] = self.goods.to_dict()

        if self.user:
            d['user'] = self.user.to_dict()

        return d

    class Meta:
        db_table = 'comments'

# 操作指南
class Operatingguide(BaseModel):
    title = models.CharField(max_length=512)
    content = models.CharField(max_length=1024)

    def to_dict(self):
        return dict(
            id=self.id,
            title=self.title,
            content=self.content,
        )

    class Meta:
        db_table = 'operatingguides'


# 团队
class Team(BaseSimpleModel):
    name = models.CharField(max_length=256, default='')
    city = models.CharField(max_length=128, default='')
    desc = models.CharField(max_length=1024, default='')
    honer = models.CharField(max_length=1024, default='')
    owner = models.ForeignKey(User, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    score = models.FloatField(default=0)
    score_total = models.IntegerField(default=0)
    score_num = models.IntegerField(default=0)

    @property
    def get_team_tag(self):
        team_list = VideoOrder.objects.filter(team_id=self.id).all()
        return '样片团队' if team_list else ''

    @property
    def get_owner_phone(self):
        if not self.owner:
            return ''
        return self.owner.phone if self.owner.phone else ''

    def get_team_members(self):
        producer_list = Producer.objects.filter(team_id=self.id).order_by('-level').all()
        rslt = []
        for p in producer_list:
            rslt.append(p.to_dict())
        return rslt

    def to_order_dict(self):
        return {
            'owner_avatar': self.get_field_property('owner', 'avatar'),
            'owner_nickname': self.get_field_property('owner', 'nickname'),
            'owner_position': '负责人',
            'team_name': self.name,
        }

    def to_detail_dict(self):
        return {
            'name': self.name,
            'desc': self.desc,
            'honer': self.honer,
            'city': self.city,
            'score': self.score,
            'members': self.get_team_members()
        }

    def to_dict(self, pic):
        return {
            'id': self.id,
            'name': self.name,
            'score': self.float_2_str(self.score),
            'team_tag': self.get_team_tag,
        }

    class Meta:
        db_table = 'teams'


# 生产者
class Producer(BaseSimpleModel):
    user = models.ForeignKey(User, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    team = models.ForeignKey(Team, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    school = models.CharField(max_length=256, default='')
    honer = models.CharField(max_length=1024, default='')
    experience = models.CharField(max_length=64, default='')
    score = models.FloatField(default=0)
    score_total = models.IntegerField(default=0)
    score_num = models.IntegerField(default=0)
    level = models.IntegerField('用户等级 1 leader, 0 普通成员', default=0)
    desc = models.CharField('个人简介', max_length=1024, default='')
    elements = models.ManyToManyField(Element, verbose_name='专业策划团队对应的具体角色', null=True, default='', blank='')

    @property
    def level_desc(self):
        return '负责人' if self.level == 1 else ''

    def elements_name(self):
        name_list = []
        for e in self.elements.all():
            name_list.append(e.name)
        return '; '.join(name_list)

    def to_dict(self, photo_style=''):
        return {
            'id': self.id,
            'avatar': self.get_field_property('user', 'avatar'),
            'nickname': self.get_field_property('user', 'nickname'),
            'city': self.get_field_property('user', 'city'),
            'mobile': self.get_field_property('user', 'phone'),
            'score': self.score,
            'team_name': self.get_field_property('team', 'name'),
            'self_desc': self.desc,
            'level_desc': self.level_desc,
            'school': self.school,
            'experience': self.experience,
            'honer': self.honer,
            'elements_name': self.elements_name(),
        }

    class Meta:
        db_table = 'producers'


class VideoType(BaseModel):
    name = models.CharField(max_length=256, default='')
    categories = models.ManyToManyField(Category, verbose_name='专业策划团队对应的具体角色', null=True, default='', blank='')


    def to_dict(self):
        return dict(
            id=self.id,
            name=self.name
        )

    class Meta:
        db_table = 'video_type'


class Tag(BaseModel):
    name = models.CharField(max_length=256)
    create_time = models.DateTimeField()
    update_time = models.DateTimeField()
    state = models.IntegerField()
    show_order = models.IntegerField()

    def to_dict(self):
        return dict(
            id=self.id,
            name=self.name
        )

    class Meta:
        db_table = 'tags'


class VideoCity(BaseModel):
    name = models.CharField('标题', max_length=256, unique=False, blank=True)
    show_order = models.IntegerField()

    def to_dict(self):
        d = {
            'id': self.id,
            'name': self.name,
        }
        return d

    class Meta:
        db_table = 'citys'


class Video(BaseModel):
    title = models.CharField('标题', max_length=256, default='')
    sub_title = models.CharField('副标题', max_length=256, default='')
    content = models.CharField('副标题下面的说明', max_length=512, default='')
    image_file = models.CharField('封面', max_length=255, default='')
    url = models.CharField('视频地址', max_length=255, default='')
    play_time = models.IntegerField(default=0)
    ini_play_time = models.IntegerField(default=0)
    desc = models.CharField('配置的文案', max_length=1024)
    sub_desc = models.CharField('产出的文案', max_length=1024)
    video_type = models.ForeignKey(VideoType, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    team = models.ForeignKey(Team, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    elements = models.ManyToManyField(Element, through='VideoElement')
    tags = models.ManyToManyField(Tag, verbose_name='专业策划团队对应的具体角色', null=True, default='', blank='')
    user_price = models.IntegerField(default=0)
    extra_price = models.IntegerField(default=0)
    video_source = models.IntegerField('1单品2样片', default=2)
    detail = models.CharField('单品详情的图片地址', max_length=2048)
    sold_num = models.IntegerField(default=0)
    ini_sold_num = models.IntegerField(default=0)
    price_unit = models.CharField('单品用到的价格单位比如1个人多少钱1天多少钱此时user_price就是单价', max_length=32)
    tips = models.CharField(max_length=512)
    shoot_day = models.IntegerField(default=0)
    duration = models.IntegerField(default=0)

    def to_dict(self, photo_style=''):
        data = dict(
            id=self.id,
            title=self.title,
            sub_title=self.sub_title,
            content=self.content,
            image_file=self.image_file,
            play_time=self.play_time + self.ini_play_time,
            desc=self.desc,
            sub_desc=self.sub_desc,
            user_price=self.user_price/100,
            video_source=self.video_source,
            detail=self.detail.split(','),
            sold_num=self.sold_num + self.ini_sold_num,
            price_unit=self.price_unit,
            tips=self.tips,
            shoot_day=self.shoot_day,
            duration=self.duration,
        )
        if self.tags:
            data['tags'] = [{'tag_id': key.id, 'tag_name': key.name} for key in self.tags.all()]
        if self.video_type:
            data['video_type'] = self.video_type.name
        return data

    def v_detail(self):
        data = dict(
            title=self.title,
            sub_title=self.sub_title,
            content=self.content,
            image_file=self.image_file,
            play_time=self.play_time + self.ini_play_time,
            desc=self.get_elements_info(),
            sub_desc=self.sub_desc,
            user_price=self.user_price/100,
            extra_price=self.extra_price/100,
            video_source=self.video_source,
            detail=self.detail.split(','),
            sold_num=self.sold_num + self.ini_sold_num,
            price_unit=self.price_unit,
            tips=self.tips,
            shoot_day=self.shoot_day,
            duration=self.duration,
        )
        if self.tags:
            data['tags'] = [{'tag_id': key.id, 'tag_name': key.name} for key in self.tags.all()]
        if self.video_type:
            data['video_type'] = self.video_type.name
        # elements = VideoElement.objects.filter(video=self).all()
        # if elements:
        #     data['elements'] = [{'name': key.element.name, 'num': key.num} for key in elements]
        return data

    def get_elements_info(self):
        order_elments = VideoElement.objects.filter(video=self).all()
        if not order_elments:
            return ''
        elements_desc_list = []
        for oe in order_elments:
            elements_desc_list.append(('%s x %s') % (oe.element.name, oe.num))
        return ' | '.join(elements_desc_list)

    class Meta:
        db_table = 'videos'


class VideoElement(BaseModel):
    video = models.ForeignKey(Video, verbose_name='订单', null=True, on_delete=models.DO_NOTHING)
    element = models.ForeignKey(Element, verbose_name='元素', null=True, on_delete=models.DO_NOTHING)
    num = models.IntegerField('元素数量')

    class Meta:
        db_table = 'video_element'


class Serie(BaseModel):
    name = models.CharField(max_length=256, default='')
    videos = models.ManyToManyField(Video, through='SerieVideo')

    class Meta:
        db_table = 'series'


class SerieVideo(BaseModel):
    video = models.ForeignKey(Video, verbose_name='订单', null=True, on_delete=models.DO_NOTHING)
    img_url = models.CharField(max_length=512, default='')
    serie = models.ForeignKey(Serie, verbose_name='元素', null=True, on_delete=models.DO_NOTHING)

    class Meta:
        db_table = 'serie_video'


class Recommend(BaseModel):
    name = models.CharField(max_length=256, default='')
    img_url = models.CharField(max_length=512, default='')
    type = models.IntegerField('1视频2系列', default=0)
    serie = models.ForeignKey(Serie, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    video = models.ForeignKey(Video, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)

    def to_dict(self):
        data = dict(
            img_url=self.img_url,
            type=self.type,

        )
        if self.serie:
            data['serie'] = self.serie.id
        if self.video:
            data['video'] = self.video.id
        return data

    class Meta:
        db_table = 'recommends'


class VideoOrderManager(models.Manager):

    def get_min_and_max_datetime(self, datetime_list):
        min_datetime = None
        max_datetime = None
        for d in datetime_list:
            if not d:
                continue
            if not min_datetime:
                min_datetime = d
            else:
                if d < min_datetime:
                    min_datetime = d
            if not max_datetime:
                max_datetime = d
            else:
                if d > max_datetime:
                    max_datetime = d
        return min_datetime, max_datetime

    def order_can_pending(self, order_id):
        """判断订单是否可以手动派单或自动派单
        """
        order = self.get_queryset().filter(order_id=order_id).first()
        if not order:
            return False
        if order.producer_type == VideoOrder.OVERALL_CONTRACTING:
            order_team = OrderTeam.objects.filter(order=order).first()
            if not order_team:
                return False
            # for field in ['edit_start_time', 'edit_end_time', 'photo_start_time', 'photo_end_time', 'plan_start_time', 'plan_end_time']:
            for field in ['start_time', 'end_time']:
                if not getattr(order_team, field):
                    return False
        else:
            order_producers = OrderProducer.objects.filter(order=order).all()
            if not order_producers:
                return False
            for op in order_producers:
                if not op.start_time or not op.end_time:
                    return False
        return True

    def update_start_and_end_time(self, order_id):
        """更新订单的开始时间，结束时间
        """
        order = self.get_queryset().filter(order_id=order_id).first()
        if not order:
            return
        if order.producer_type == VideoOrder.OVERALL_CONTRACTING:
            order_team = OrderTeam.objects.filter(order=order).first()
            time_list = [
                order_team.start_time,
                order_team.end_time,
                order_team.edit_start_time,
                order_team.edit_end_time,
                order_team.photo_start_time,
                order_team.photo_end_time,
                order_team.plan_start_time,
                order_team.plan_end_time
            ]
        else:
            order_producers = OrderProducer.objects.filter(order=order).all()
            time_list = []
            for op in order_producers:
                time_list.append(op.start_time)
                time_list.append(op.end_time)
        min_datetime, max_datetime = self.get_min_and_max_datetime(time_list)
        if min_datetime and max_datetime:
            order.start_time = min_datetime
            order.end_time = max_datetime
            order.save()

    def update_order_status(self, order_id):
        """更新订单状态
            分包时，各分包角色都已经配置了人，状态进入编剧中
        """
        order = self.get_queryset().filter(order_id=order_id).first()
        if not order:
            return
        order_producers = OrderProducer.objects.filter(order=order).all()
        start_plan = True
        for op in order_producers:
            if not op.producer_id:
                start_plan = False
                break
        if start_plan:
            order.order_status = VideoOrder.STATE_WRITING
            order.save()
        return start_plan

# (0, '待付款'),
# (1, '待派单'),
# (2, '匹配团队中'),
# (4, '待启动'),
# (5, '编剧中'),
# (6, '拍摄中'),
# (7, '剪辑中'),
# (8, '待验收'),
# (3, '待评论'),
# (9, '退款中'),
# (10, '已退款'),
# (11, '已完成'),
# (12, '已取消'),
# (99, '购物车');
# (999, '无效订单');
# 创建好订单后会在OrderElement，OrderProducer，OrderTeam创建好数据OrderProducer，OrderTeam，state设置为1
# state为1标识没启用，当项目经理决定整包还是分包的时候
# 整包OrderTeam的state为0分包则将OrderProducer改成0，同时只有一边为0

class VideoOrder(BaseModel):
    STATE_OBLIGATIONS, STATE_PENDING_ORDERS, STATE_MATCHING_TEAM = 0, 1, 2
    STATE_PENDING_START, STATE_WRITING, STATE_SHOOTING = 4, 5, 6
    STATE_CLIP, STATE_PENDING_ACCEPTANCE, STATE_PENDING_COMMENTS = 7, 8, 3
    STATE_REFUNDING, STATE_REFUNDS, STATE_FINISH = 9, 10, 11
    STATE_CACEL, STATE_SHOPPING_CART = 12, 99

    city = models.CharField(max_length=256, default='')
    second_city = models.CharField(max_length=256, default='')
    requirement = models.CharField('用户需求', max_length=1024, default='')
    plan_suggest = models.CharField('策划建议', max_length=1024, default='')
    user_remark = models.CharField('用户备注', max_length=1024)
    contact = models.CharField(max_length=256)
    phone = models.CharField(max_length=256)
    user = models.ForeignKey(User, related_name='user', verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    manager = models.ForeignKey(User, related_name='manager', verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    order_status = models.IntegerField(default=-1)
    shoot_day = models.IntegerField('拍摄天数')
    video_duration = models.IntegerField('视频时长')
    video_type = models.ForeignKey(VideoType, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    back_amount = models.IntegerField('退款金额最小单位分', default=0)
    pay_amount = models.IntegerField('已支付金额', default=0)
    first_pay_amount = models.IntegerField('首付款', default=0)
    secend_pay_amount = models.IntegerField('验收款', default=0)
    amount = models.IntegerField('总共需要支付的金额', default=0)
    price = models.IntegerField('原始价格包含优惠', default=0)
    weixin_order_id = models.CharField(max_length=64, default='')
    second_weixin_order_id = models.CharField(max_length=64, default='')
    order_id = models.CharField('支付用到的业务id', max_length=64, default='')
    second_order_id = models.CharField('支付用到的业务id', max_length=64, default='')
    tax_unit = models.CharField(max_length=512, default='')
    tax_code = models.CharField(max_length=512, default='')
    agree_show = models.IntegerField('0不展示1展示', default=0)
    need_tax = models.IntegerField('0不需要1需要', default=0)
    back_remark = models.CharField('退款申请备注', max_length=512)
    producer_type = models.IntegerField('0分包1整包', default=0)
    start_time = models.DateTimeField(null=True)
    end_time = models.DateTimeField(null=True)
    photo_time = models.DateTimeField('用户设置的拍摄时间', null=True)
    order_from_type = models.IntegerField('1单品2样片3定制化', default=1)
    team = models.ForeignKey(Team, verbose_name='样片或者单品的团队', null=True, on_delete=models.DO_NOTHING)
    video = models.ForeignKey(Video, verbose_name='样片或者单品的视频', null=True, on_delete=models.DO_NOTHING)
    title = models.CharField(max_length=512, default='')
    elements = models.ManyToManyField(Element, through='OrderElement')
    objects = VideoOrderManager()

    SUB_CONTRACTING, OVERALL_CONTRACTING = 0, 1

    STATE_DESC_DICT = {
        0: '待付款',
        1: '待派单',
        2: '匹配团队中',
        4: '待启动',
        5: '编剧中',
        6: '拍摄中',
        7: '剪辑中',
        8: '待验收',
        3: '待评论',
        9: '退款中',
        10: '已退款',
        11: '已完成',
        12: '已取消',
        99: '购物车',
    }

    def user_order_detail(self):
        data = dict(
            id=self.id,
            order_id=self.order_id,
            video_type=self.video_type.name,
            order_type=self.order_from_type,
            video_duration='%s 分钟' % self.video_duration,
            shoot_day=self.shoot_day,
            amount=self.amount*0.01,
            photo_time=self.photo_time,
            create_time=self.create_time.strftime('%Y-%m-%d'),
            contact=self.contact,
            phone=self.phone,
            order_status=self.order_status,
            tax_unit=self.tax_unit,
            tax_code=self.tax_code,
            need_tax=self.need_tax,
            city=self.city,
            nickname= self.get_user_field('nickname'),
            user_remark=self.user_remark,
            title=self.title
        )
        data['other_info'] = self.get_elements_info()
        if self.video:
            data['video_id']=self.video.id
            data['video_title'] = self.video.title
        return data

    def producer_simple_info(self):
        return dict(
            id=self.id,
            shoot_day=self.shoot_day,
            video_duration=self.video_duration,
            video_type=self.video_type.name,
            order_no=self.order_id,
            title=self.title,

        )

    def order_elements(self):
        order_elments = OrderElement.objects.filter(order=self).all()
        data = []
        for oe in order_elments:
            oet = oe.element.to_dict()
            oet['num'] = oe.num
            data.append(oet)
        return data

    def get_user_field(self, field):
        if not self.user:
            return ''
        return getattr(self.user, field, '')

    def get_elements_info(self):
        order_elments = OrderElement.objects.filter(order=self).all()
        if not order_elments:
            return ''
        elements_desc_list = []
        for oe in order_elments:
            elements_desc_list.append(('%s x %s') % (oe.element.name, oe.num))
        return ' | '.join(elements_desc_list)

    @property
    def order_type_desc(self):
        if self.order_from_type == 1:
            return '单品订单'
        elif self.order_from_type == 2:
            return '样片订单'
        elif self.order_from_type == 3:
            return '定制订单'
        return ''

    def get_producers_info(self):
        order_producers = OrderProducer.objects.filter(order=self).all()
        rslt = {}
        for op in order_producers:
            tmp_dict = op.to_order_dict()
            key = 'persons' if tmp_dict.get('type') == Element.TYPE_PERSON else 'equips'
            rslt.setdefault(key, []).append(tmp_dict)
        return rslt

    def get_overall_contracting_info(self):
        order_team = OrderTeam.objects.filter(order=self).first()
        return order_team.to_pending_dict() if order_team else {}

    def get_sub_contracting_info(self):
        order_producers = OrderProducer.objects.filter(order=self).order_by('element_id').all()
        rslt = {}
        for op in order_producers:
            category_name = op.element.category_set.first().name
            rslt.setdefault(category_name, {'value': category_name, 'list': []}).get('list').append(op.to_pending_dict())
        data = [value for key, value in rslt.items()]
        return data

    def contracting_info(self):
        producer_type = self.producer_type
        rslt = {}

        if producer_type == VideoOrder.OVERALL_CONTRACTING:
            rslt['overall_contract_info'] = self.get_overall_contracting_info()
        else:
            rslt['sub_contract_info'] = self.get_sub_contracting_info()
        # if self.state in [ VideoOrder.STATE_PENDING_ORDERS, VideoOrder.STATE_MATCHING_TEAM, VideoOrder.STATE_PENDING_START,
        #                 VideoOrder.STATE_WRITING, VideoOrder.STATE_SHOOTING, VideoOrder.STATE_CLIP, VideoOrder.STATE_PENDING_ACCEPTANCE,
        #                 VideoOrder.STATE_PENDING_COMMENTS ]:
        #     if producer_type == VideoOrder.OVERALL_CONTRACTING:
        #         rslt['overall_contract_info'] = self.get_overall_contracting_info()
        #     else:
        #         rslt['sub_contract_info'] = self.get_sub_contracting_info()
        # elif self.state in [ VideoOrder.STATE_REFUNDS, VideoOrder.STATE_FINISH ]:
        #     if producer_type == VideoOrder.OVERALL_CONTRACTING:
        #         rslt['team_info'] = self.team.to_order_dict()
        #     else:
        #         rslt['producers_info'] = self.get_producers_info()
        return rslt

    def to_detail_dict(self):
        data = self.to_dict()
        data['video_type_name'] = self.get_field_property('video_type', 'name')
        data['video_duration'] = '%s分钟' % self.video_duration
        data['shoot_day'] = self.shoot_day
        data['city'] = self.city
        data['video_name'] = self.get_field_property('video', 'title')
        data['video_url'] = self.get_field_property('video', 'url')
        data['start_time'] = self.format_datetime(self.start_time)
        data['end_time'] = self.format_datetime(self.end_time)
        data['state_desc'] = VideoOrder.STATE_DESC_DICT.get(self.order_status)
        data['producer_type'] = self.producer_type
        data['current_time'] = datetime.now().strftime('%Y-%m-%d')
        contracting_info = self.contracting_info()
        if contracting_info:
            for key, val in contracting_info.items():
                data[key] = val
        return data

    def to_dict(self, photo_style=''):
        return {
            'id':self.id,
            'avatar': self.get_user_field('avatar'),
            'nickname': self.get_user_field('nickname'),
            'create_time': self.create_time.strftime('%Y-%m-%d'),
            'start_time': self.format_datetime(self.start_time),
            'end_time': self.format_datetime(self.end_time),
            'current_time': self.format_datetime(datetime.now()),
            'order_id': self.order_id,
            'order_type': self.order_type_desc,
            'element_detail': self.get_elements_info(),
            'amount': int(self.amount * 0.01),
            'state': self.order_status,
            'producer_type': self.producer_type,
            'phone': self.phone,
            'title':self.title,
            'has_manager': False if (not self.manager_id and self.order_status == VideoOrder.STATE_PENDING_ORDERS) else True,
        }

    class Meta:
        db_table = 'orders'


class OrderElement(BaseModel):
    order = models.ForeignKey(VideoOrder, verbose_name='订单', null=True, on_delete=models.DO_NOTHING)
    element = models.ForeignKey(Element, verbose_name='元素', null=True, on_delete=models.DO_NOTHING)
    num = models.IntegerField('元素数量')

    class Meta:
        db_table = 'order_elements'


class OrderProducer(BaseModel):
    DPD, PP, ZZZ, DYS, DPJ, WC, YTK = 0, 1, 9, 5, 6, 7, 8
    start_time = models.DateTimeField('角色的开始时间', null=True)
    end_time = models.DateTimeField(null=True)
    excute_day = models.IntegerField('执行天数', default=0)
    amount = models.IntegerField('分成金额', default=0)
    rate = models.FloatField('分成比例', default=0.8)
    price = models.IntegerField('原始金额', default=0)
    order = models.ForeignKey(VideoOrder, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    element = models.ForeignKey(Element, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    producer = models.ForeignKey(Producer, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    order_status = models.IntegerField('0 待派单 1匹配中，9制作中，5待验收 6待评价，7完成,8 退款', default=0)
    remark = models.CharField('项目经理评价', max_length=512, default='')
    score = models.IntegerField('项目经理评分', default=-1)
    producer_finish_time = models.DateTimeField('角色的开始时间', null=True)

    @property
    def video_type_name(self):
        order = self.order
        return order.get_field_property('video_type', 'name')

    def get_producer_user_field(self, key):
        if not self.producer or not self.producer.user:
            return ''
        return self.producer.get_field_property('user', key)

    @property
    def producer_element_name(self):
        return self.element.name if self.element else ''

    @property
    def producer_all_element_name(self):
        return self.producer.elements_name() if self.producer else ''

    def to_order_dict(self):
        return {
            'avatar': self.get_producer_user_field('avatar'),
            'nickname': self.get_producer_user_field('nickname'),
            'element_name': self.producer_element_name,
            'type': self.element.type,
            'start_time': self.format_datetime(self.start_time),
            'end_time': self.format_datetime(self.end_time),
        }

    @property
    def total_amount(self):
        amount = int(self.element.price * 0.01) if not self.amount else int(self.amount * 0.01)
        return self.excute_day * amount

    def to_pending_dict(self):
        return {
            'id': self.id,
            'producer_id': self.get_field_property('producer', 'id'),
            'avatar': self.get_producer_user_field('avatar'),
            'nickname': self.get_producer_user_field('nickname'),
            'element_name': self.producer_element_name,
            'element_id': self.element.id,
            'type': self.element.type,
            'amount': self.total_amount,
            'start_time': self.format_datetime(self.start_time),
            'end_time': self.format_datetime(self.end_time),
            'order_status': self.order_status,
            'title': self.order.title,
        }

    def to_comment_dict(self):
        return {
            'order_id': self.order.order_id,
            'id': self.id,
            'remark': self.remark,
            'score': self.score,
            'video_type_name': '【%s】' % self.video_type_name,
            'avatar': self.get_producer_user_field('avatar'),
            'nickname': self.get_producer_user_field('nickname'),
            'start_time': self.format_datetime(self.start_time),
            'element_name': self.producer_element_name,
            'title': self.order.title,
        }

    def to_dict(self, photo_style=''):
        data = dict(
            id=self.id,
            amount=float(self.amount * 0.01),
            order_status=self.order_status,
            title=self.order.title,
        )
        data['team'] = 0
        data['order'] = self.order.producer_simple_info()
        data['element'] = [self.element.to_dict()]
        if self.start_time:
            data['start_time'] = self.start_time.strftime('%Y-%m-%d')
        if self.end_time:
            data['end_time'] = self.end_time.strftime('%Y-%m-%d')
        if self.producer:
            data['producer'] = self.producer.to_dict()
        return data

    class Meta:
        db_table = 'order_producer'


class OrderTeam(BaseModel):
    DPD, PP, BJ, PS, JJ, DYS, DPJ, WC, YTK = 0, 1, 2, 3, 4, 5, 6, 7, 8
    start_time = models.DateTimeField('整个订单的开始时间', null=True)
    end_time = models.DateTimeField(null=True)
    edit_start_time = models.DateTimeField('剪辑的开始时间', null=True)
    edit_end_time = models.DateTimeField(null=True)
    photo_start_time = models.DateTimeField('拍摄的开始时间', null=True)
    photo_end_time = models.DateTimeField(null=True)
    plan_start_time = models.DateTimeField('编剧的开始时间', null=True)
    plan_end_time = models.DateTimeField(null=True)
    order = models.ForeignKey(VideoOrder, verbose_name='分类', null=True, on_delete=models.DO_NOTHING)
    team = models.ForeignKey(Team, verbose_name='样片或者单品的团队', null=True, on_delete=models.DO_NOTHING)
    amount = models.IntegerField('分成金额', default=0)
    rate = models.FloatField('分成比例', default=0.8)
    price = models.IntegerField('原始金额', default=0)
    order_status = models.IntegerField('0 待派单 1匹配团队中，2编剧，3拍摄，4剪辑，5待验收 6待评价，7完成,8 退款', default=0)
    remark = models.CharField('项目经理评价', max_length=512, default='')
    score = models.IntegerField('项目经理评分', default=-1)

    @property
    def video_type_name(self):
        order = self.order
        return order.get_field_property('video_type', 'name')

    def get_team_owner_field(self, field):
        if not self.team or not self.team.owner:
            return ''
        return self.team.get_field_property('owner', field)

    def order_team_amount(self):
        return float(self.amount * 0.01)

    def to_comment_dict(self):
        return {
            'id': self.id,
            'order_id': self.order.order_id,
            'remark': self.remark,
            'score': self.score,
            'team_name': self.get_field_property('team', 'name'),
            'video_type_name': '【%s】' % self.video_type_name,
            'owner_avatar': self.get_team_owner_field('avatar'),
            'owner_nickname': self.get_team_owner_field('nickname'),
            'start_time': self.format_datetime(self.start_time),
            'end_time': self.format_datetime(self.end_time),
            'title': self.order.title,
        }

    def to_pending_dict(self):
        return {
            'id': self.id,
            'owner_avatar': self.get_team_owner_field('avatar'),
            'owner_nickname': self.get_team_owner_field('nickname'),
            'team_name': self.get_field_property('team', 'name'),
            'start_time': self.format_datetime(self.start_time),
            'end_time': self.format_datetime(self.end_time),
            'plan_start_time': self.format_datetime(self.plan_start_time),
            'plan_end_time': self.format_datetime(self.plan_end_time),
            'photo_start_time': self.format_datetime(self.photo_start_time),
            'photo_end_time': self.format_datetime(self.photo_end_time),
            'edit_start_time': self.format_datetime(self.edit_start_time),
            'edit_end_time': self.format_datetime(self.edit_end_time),
            'order_status': self.order_status,
            'order_id': self.order.order_id,
            'price': self.price,
            'rate': self.rate * 100,
            'amount': self.order_team_amount(),
            'title': self.order.title,
        }

    def to_dict(self, photo_style=''):
        data = dict(
            id=self.id,
            amount=float(self.amount * 0.01),
            order_status=self.order_status,
            title=self.order.title,
        )
        data['order'] = self.order.producer_simple_info()
        data['team'] = 1
        data['element'] = self.order.order_elements()
        # if self.order_status == self.BJ:
        #     if self.plan_start_time:
        #         data['start_time'] = self.plan_start_time.strftime('%Y-%m-%d')
        #     if self.plan_end_time:
        #         data['end_time'] = self.plan_end_time.strftime('%Y-%m-%d')
        # elif self.order_status == self.PS:
        #     if self.photo_start_time:
        #         data['start_time'] = self.photo_start_time.strftime('%Y-%m-%d')
        #     if self.photo_end_time:
        #         data['end_time'] = self.photo_end_time.strftime('%Y-%m-%d')
        #
        # elif self.order_status == self.JJ:
        #     if self.edit_start_time:
        #         data['start_time'] = self.edit_start_time.strftime('%Y-%m-%d')
        #     if self.edit_end_time:
        #         data['end_time'] = self.edit_end_time.strftime('%Y-%m-%d')
        # else:
        if self.start_time:
            data['start_time'] = self.start_time.strftime('%Y-%m-%d')
        if self.end_time:
            data['end_time'] = self.end_time.strftime('%Y-%m-%d')
        return data

    class Meta:
        db_table = 'order_team'
